(ns redrouter.core
  (:require
   [reagent.core :as r]
   [reagent.dom :as dom]
   ["react-router-dom" :as rd]
   [redrouter.utils :as utils])
  (:require-macros
   [redrouter.macros :refer [export-react-router-hooks
                              export-react-router-components]]))

(export-react-router-hooks)
(export-react-router-components)

(defn- ->route [r render]
  [route
   {:path (utils/get-route-paths r)
    :exact (if (boolean? (:exact r)) (:exact r) true)
    :render (fn [p]
              (let [props (js->clj p :keywordize-keys true)]
                (r/as-element (render r props))))}])

(defn- get-sub-router
  "子路由"
  [sub-route route-props]
  (let [{:keys [routes]} sub-route]
    (if (seq (:redirect sub-route))
      [redirect {:to (:redirect sub-route)}]
      (let [components (utils/get-route-compoents sub-route)]
        (if (seq routes)
          (utils/wrapper-compoents
           components
           route-props
           (into
            [switch]
            (mapv #(->route % get-sub-router) routes)))
          (utils/wrapper-compoents components route-props))))))

(defn- root-component [config]
  (let [router (if (:hash? config) hash-router browser-router)]
    [router
     (into
      [switch]
      (mapv #(->route % get-sub-router) (:routes config)))]))

(def ^:private default-options
  {:root-id "app"
   :routes []
   :hash? false})

(defn start! [options]
  ;; TODO check options
  (let [config (merge default-options options)]
    (dom/render
     (root-component config)
     (. js/document (getElementById (:root-id config))))))
